<style>
  .data_operation {
        border: 1px solid #bbc;
        /* right: 20px !important; */
        padding: 8px 10px;
        border-radius: 5px;
        left: 78%;
    }
    
    .orgManagerWrap {
        border-radius: 5px;
    }
    
    .el-popover {
        min-width: 80px;
    }
    
    .pup {
        margin-bottom: 10px !important;
    }
    
    .orgManager .el-table--enable-row-hover .el-table__body tr:hover>td {
        background-color: #B7D9FC !important;
    }
    
    .orgManager .el-dropdown .el-dropdown-menu .el-dropdown-item:hover {
        background-color: #B7D9FC;
    }
    
    .el-button:focus,
    .el-button:hover {
        background-color: #B7D9FC !important;
    }
    
    .lookRow {
        color: #44CEF6;
    }
    
    .lookRow:hover {
        padding: 5px;
        color: #44CEF6;
    }
</style>
<template>
  <div class="orgManager w944">
    <alert ref="alert"></alert>
    <deleteAlert ref="deleteAlert"></deleteAlert>
    <div class="label_top">
      <p><i class="line"></i>组织管理</p>
    </div>
    <div class="label_table">
      <div class="el-tabs-report">
        <a class="listOne" @click="createOrganization">新增组织</a>
        <el-cascader v-model="value" style="margin-left:20px" :options="cityArr" :props="optionProps" @change="cityArrChange"
          placeholder="选择地区"></el-cascader>

        <div class="msearch" style="right: 180px !important">
          <input placeholder="请输入组织名称、编号、地区……" v-model="search" />
          <a @click="getPageSearch"><img src="../../assets/qudaoImg/search.png" /></a>
        </div>

        <el-dropdown trigger="click" class="data_operation">
          <span class="el-dropdown-link">数据操作</span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item><span @click="">导入用户</span></el-dropdown-item>
            <el-dropdown-item><span @click="">导出用户</span></el-dropdown-item>
            <el-dropdown-item><span @click="">导入部门</span></el-dropdown-item>
            <el-dropdown-item><span @click="">导出部门</span></el-dropdown-item>
            <el-dropdown-item><span @click="">导入机构</span></el-dropdown-item>
            <el-dropdown-item><span @click="">导出机构</span></el-dropdown-item>
            <el-dropdown-item><span @click="">下载模板</span></el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>

      <el-table :data="tableData" border row-key="id" :tree-props="{children: 'children'}" lazy :load="expandChange"
        ref="table">
        <el-table-column v-for="(item,index) in tableList" :key="index" :label="item.label" :prop="item.prop">
        </el-table-column>
        <el-table-column label="地区">
          <template slot-scope="scope">
            <span>{{scope.row.area}}</span>
          </template>
        </el-table-column>
        <el-table-column label="员工" width="200">
          <template slot-scope="scope">
            <p class="lookRow" @click="handleSeen(scope.row)">查看员工</p>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-popover trigger="hover" style="width:80" placement="top">
              <p class="pup" @click="addOrganization(scope.row)">新增子组织</p>
              <p class="pup" @click="handleEdit(scope.row)">编辑</p>
              <p class="pup" v-if="!scope.row.move">
                <el-popover placement="left-start" trigger="click">
                  <p slot="reference" @click="ChangeIsPart(scope.row)">变更隶属</p>
                  <div class="moveAll">
                    <el-tree :data="organizationArr" :props="defaultProps" @node-click="handleNodeClickMove"></el-tree>
                  </div>
                </el-popover>
              </p>
              <p class="pup" type="danger" @click="handleDelete(scope.row)">删除</p>
              <div slot="reference" class="name-wrapper">
                <img src="../../assets/qudaoImg/slhCol.png" />
              </div>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <div class="fenyeMargin">
        <div class="pag_block">
          <el-pagination @current-change="handleCurrentChange" :current-page="currentpage" :page-size="pagesize" layout="prev, pager, next"
            :total="total"></el-pagination>
        </div>
      </div>
    </div>
    <!--添加组织-->
    <div class="orgManagerWrap" v-show="addOrgPage">
      <div class="bd_line">
        <span>组织名称:</span>
        <input type="text" style="width: 60%;" placeholder="请输入组织名称" v-model="name">
      </div>
      <div class="bd_line" v-if="nowType=='edit'">
        <span>组织编号:</span>
        <em>{{serialNumber}}</em>
      </div>
      <div class="bd_line">
        <span>所在地区:</span>
        <el-cascader v-model="valueWrap" :options="cityArr" :props="optionProps" placeholder="选择地区" @change="cityArrChangeAdd"></el-cascader>
      </div>
      <div class="bd_line" style="height: 80px;">
        <span>组织描述:</span>
        <textarea placeholder="请输入更新内容..." v-model="describes" style="width: 60%;position: absolute;left: 112px;top: 0;"></textarea>
      </div>
      <div class="footerButton">
        <a @click="checkSave">保存</a>
        <a @click="cancel" class="cancel">取消</a>
      </div>
    </div>
  </div>
</template>
<script>
  import alert from '../../components/Alert.vue';
  import deleteAlert from '../../components/deleteAlert.vue';
  export default {
    data() {
      return {
        orgManager: '',
        proviceid: '',
        proviceidArr: [],
        cityid: '',
        cityidArr: [],
        regionid: '',
        regionidArr: [],
        search: '',
        tableData: [],
        multipleSelection: [],
        currentIndex: 0,
        tableDataChild: [],
        nowType: 'add',
        pid: 0,
        editId: '',
        editPid: '',
        addOrgPage: false,
        name: '',
        serialNumber: '',
        describes: '',
        proviceidWrap: '',
        cityidWrap: '',
        regionidWrap: '',
        rootcompanyidWrap: '',

        pagesize: 15,
        currentpage: 1,
        total: 1,
        deleteType: 'delete',

        cityArr: [],
        valueWrap: [],
        value: [],
        filterText: '',
        optionProps: {
          value: 'id',
          label: 'name',
          children: 'list',
        },
        tempRootCompanyId: '',
        tableList: [{
          label: "组织",
          prop: "name"
        }],
        loadNodeMap: new Map(),
        moveAll: false,
        organizationArr: [],
        defaultProps: {
          children: 'childrenList',
          label: 'name'
        },
        newOrgId: [],
      }
    },
    methods: {
      cityArrChange(data) {
        this.proviceid = data[0];
        if (data[1] != undefined) {
          this.cityid = data[1];
        } else {
          this.cityid = '';
        };
        if (data[2] != undefined) {
          this.regionid = data[2];
        } else {
          this.regionid = '';
        };
        this.getTableList();
      },
      getTableList() {
        this.$ajax({
          url: this.$root.jifuUrl + "/getOrganizationPage?" + 'page=' + this.currentpage + '&num=' + this.pagesize +
            '&rootcompanyid=1' + '&proviceid=' + this.proviceid + '&cityid=' + this.cityid + '&regionid=' + this.regionid +
            '&name=' + this.search,
          method: 'GET',
          data: {},
          success: res => {
            if (res.data.code == 200) {
              this.tableData = res.data.data.list;
              this.tableData.forEach(element => {
                this.newOrgId.push(element.id)
                console.log('--getTableList--this.newOrgId--', this.newOrgId)
                element.area = element.proviceName + (element.cityName != null ? "-" + element.cityName : "") +
                  (element.regionName != null ? "-" + element.regionName : "")
                element.hasChildren = true;
                if (this.newOrgId.includes(element.id)) {
                  element.move = true;
                  console.log('--element.id--', element.id)
                } else {
                  element.move = false;
                }
              });
              // console.log('--getTableList--', this.tableData)
              this.total = res.data.data.pageParam.items;
            }
          }
        });
      },
      getTreeDataCity(data) {
        for (var i = 0; i < data.length; i++) {
          if (data[i].list.length < 1) {
            data[i].list = undefined;
          } else {
            this.getTreeDataCity(data[i].list);
          }
        }
        return data;
      },
      createOrganization() {
        this.addOrgPage = true
      },
      cityArrChangeAdd(data) {
        this.proviceid = data[0];
        if (data[1] != undefined) {
          this.cityid = data[1];
        } else {
          this.cityid = '';
        };
        if (data[2] != undefined) {
          this.regionid = data[2];
        } else {
          this.regionid = '';
        };
      },
      add_type() {
        let s = {
          rootcompanyid: 1,
          name: this.name,
          pid: this.pid,
          proviceid: this.proviceid,
          cityid: this.cityid,
          regionid: this.regionid,
          describes: this.describes
        };
        if (this.name == '') {
          this.wrapClose = true;
          this.stateWrapText = '组织名称为空！';
        } else {
          this.$ajax({
            url: this.$root.jifuUrl + '/addOrganization',
            method: 'POST',
            data: this.qs.stringify(s),
            success: res => {
              if (res.data.code == 200) {
                this.addOrgPage = false;
                this.wrapClose = true;
                this.stateWrapText = '保存成功';
                setTimeout(() => {
                  this.$router.go(0);
                }, 2000)
              } else {
                this.addOrgPage = false;
                this.wrapCloseSecond = true;
                this.stateWrapTextSecond = res.data.message;
              }
            }
          });
        }
      },
      addOrganization(row) {
        this.selectRow = row;
        this.addOrgPage = true;
        this.nowType = 'childAdd';
        this.transitionAddId = row.id;
      },
      add_child_type() {
        let s = {
          rootcompanyid: 1,
          name: this.name,
          pid: this.transitionAddId,
          proviceid: this.proviceid,
          cityid: this.cityid,
          regionid: this.regionid,
          describes: this.describes
        };
        if (this.name == '') {
          this.wrapClose = true;
          this.stateWrapText = '组织名称为空！';
        } else {
          this.$ajax({
            url: this.$root.jifuUrl + '/addOrganization',
            method: 'POST',
            data: this.qs.stringify(s),
            success: res => {
              if (res.data.code == 200) {
                this.addOrgPage = false;
                this.wrapClose = true;
                this.stateWrapText = '保存成功';
                setTimeout(() => {
                  this.$router.go(0);
                }, 2000)
              } else {
                this.addOrgPage = false;
                this.wrapCloseSecond = true;
                this.stateWrapTextSecond = res.data.message;
              }
            }
          });
        }
      },
      edit_type() {
        if (this.cityid == '') {
          this.cityid = -1;
        };
        if (this.regionid == '') {
          this.regionid = -1;
        };
        let s = {
          rootcompanyid: 1,
          name: this.name,
          id: this.editId,
          pid: this.editPid,
          proviceid: this.proviceid,
          cityid: this.cityid,
          regionid: this.regionid,
          describes: this.describes
        };
        this.$ajax({
          url: this.$root.jifuUrl + '/updateOrganization',
          method: 'POST',
          data: this.qs.stringify(s),
          success: res => {
            if (res.data.code == 200) {
              this.addOrgPage = false;
              this.wrapClose = true;
              this.stateWrapText = '保存成功';
              setTimeout(() => {
                this.$router.go(0);
              }, 2000)
            } else {
              this.addOrgPage = false;
              this.wrapCloseSecond = true;
              this.stateWrapTextSecond = res.data.message;
            }
          }
        });
      },
      checkSave() {
        if (this.nowType == 'add') {
          this.add_type();
        } else if (this.nowType == 'childAdd') {
          this.add_child_type();
        } else if (this.nowType == 'edit') {
          this.edit_type();
        }
      },
      cancel() {
        this.addOrgPage = false;
        this.name = '';
        this.valueWrap = [];
        this.describes = '';
      },
      handleEdit(item) {
        this.selectRow = item;
        this.addOrgPage = true;
        this.nowType = 'edit';
        this.$ajax({
          url: this.$root.jifuUrl + '/getOrganizationById?' + 'id=' + item.id,
          method: 'GET',
          data: {},
          success: res => {
            if (res.data.code == 200) {
              this.editId = res.data.data.id;
              this.editPid = res.data.data.pid;
              this.rootcompanyidWrap = res.data.data.rootcompanyid;
              this.name = res.data.data.name;
              this.serialNumber = res.data.data.no;
              this.proviceid = res.data.data.proviceid;
              this.cityid = res.data.data.cityid;
              this.regionid = res.data.data.regionid;
              if (this.cityid == undefined) {
                this.valueWrap = [this.proviceid];
              } else if (this.regionid == undefined) {
                this.valueWrap = [this.proviceid, this.cityid];
              } else {
                this.valueWrap = [this.proviceid, this.cityid, this.regionid];
              };
              this.describes = res.data.data.describes;
            } else {
              this.wrapCloseSecond = true;
              this.stateWrapTextSecond = res.data.message;
            }
          }
        });
      },
      handleDelete(row) {
        this.selectRow = row;
        this.deleteStatus = true;
        this.transitionRow = row.id;
        this.$rootFunction().rootDelete();
      },
      deleteSubmit() {
        let s = {
          ids: this.transitionRow
        };
        this.$ajax({
          url: this.$root.jifuUrl + "/deleteOrganization",
          method: 'POST',
          data: this.qs.stringify(s),
          success: res => {
            if (res.data.code == 200) {
              this.deleteStatus = false;
              this.wrapClose = true;
              setTimeout(() => {
                this.$router.go(0);
              }, 1000)
            } else {
              this.failText = res.data.message;
              this.$rootFunction().deleteResFail();
            }
          }
        });
      },
      deleteCancel() {
        this.deleteStatus = false;
        this.nowTypeDelete = 'delete';
      },
      handleSeen(row) {
        console.log(row);
        this.$router.push({
          name: 'userManager',
          params: {
            id: row.id,
            name: row.name,
          }
        })
      },
      expandChange(row, treeNode, resolve) {
        var id = row.id;
        if (!this.loadNodeMap.has(id)) {
          this.loadNodeMap.set(id, {
            row,
            treeNode,
            resolve
          })
        };
        row.children = [];
        this.$ajax({
          url: this.$root.jifuUrl + "/getOrganizationPage?" + 'page=' + this.currentpage + '&num=' + this.pagesize +
            '&rootcompanyid=1' + '&proviceid=' + this.proviceid + '&cityid=' + this.cityid + '&regionid=' + this.regionid +
            '&name=' + this.search + '&pid=' + row.id,
          method: 'GET',
          data: {},
          success: res => {
            if (res.data.code == 200) {
              var children = res.data.data.list;
              console.log('--expandChange--children-', children)
              children.forEach(element => {
                element.area = element.proviceName + (element.cityName != null ? "-" + element.cityName : "") +
                  (element.regionName != null ? "-" + element.regionName : "")
                element.hasChildren = true;
                if (this.newOrgId.includes(element.id)) {
                  element.move = true;
                } else {
                  element.move = false;
                }
              });
              resolve(children)
            }
          }
        });
        console.log('--expandChange--this.newOrgId--', this.newOrgId)
        console.log('--expandChange-this.tableData-', this.tableData)
      },
      getOrganizationArr() {
        this.$ajax({
          url: this.$root.jifuUrl + "/getOrganizationInfo?" + '&rootcompanyid=1' + '&proviceid=' + this.proviceid +
            '&cityid=' + this.cityid + '&regionid=' + this.regionid,
          method: 'GET',
          data: {},
          success: res => {
            if (res.data.code == 200) {
              this.organizationArr = res.data.data;
            }
          }
        });
      },
      ChangeIsPart(row) {
        this.changeId = row.id
        this.getOrganizationArr(this.rootcompanyid);
      },
      handleNodeClickMove(data) {
        var s = {
          id: this.changeId,
          pid: data.id
        };
        this.$ajax({
          url: this.$root.jifuUrl + "/moveOrganization",
          method: 'POST',
          data: this.qs.stringify(s),
          success: res => {
            if (res.data.code == 200) {
              this.wrapClose = true;
              this.stateWrapText = '操作成功';
              setTimeout(() => {
                this.wrapClose = false;
                this.getTableList();
              }, 1000)
            } else {
              this.deleteStatus = false;
              this.wrapCloseSecond = true;
              this.stateWrapTextSecond = res.data.message;
            }
          }
        });
      },
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row, !this.allSelect)
          })
          this.allSelect = !this.allSelect;
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = [];
        val.forEach(row => {
          this.multipleSelection.push(row.id);
        })
      },
      stateWrapClose() {
        this.wrapClose = !this.wrapClose;
      },
      stateWrapCloseSecond() {
        this.wrapCloseSecond = !this.wrapCloseSecond;
      },
      handleCurrentChange(value) {
        this.currentpage = value;
        this.getTableList();
      },
      getPageSearch() {
        this.currentpage = 1;
        this.getTableList();
      },
    },
    components: {
      alert,
      deleteAlert
    },
    mounted: function() {
      this.getTableList();
      this.$rootFunction().getAllCity();
      this.orgManager = this.$root.huasan.orgManager;
    }
  }
</script>

<style>
  .orgManager .el-dropdown span {
    color: #44CEF6;
    cursor: pointer;
  }

  .orgManager .el-table__row td:nth-child(4) button:nth-child(2) {
    color: #FF2D51;
    margin-left: 5px;
  }

  .orgManager .el-table__row td:nth-child(1) .cell {
    text-align: left !important;
    padding-left: 20px;
  }

  .orgManager .el-tabs-report .el-select,
  .orgManager .el-tabs-report .el-select .el-input,
  .orgManager .el-tabs-report .el-select .el-input input,
  .orgManager .el-cascader,
  .orgManager .el-cascader .el-input,
  .orgManager .el-cascader input {
    width: 180px;
  }

  .orgManager .el-tabs-report .el-dropdown {
    margin-left: 20px
  }

  .orgManager .label_table .moveAll {
    width: 200px;
    height: 180px;
    padding: 5px 20px;
    background: #fff;
  }

  .orgManager .label_table .moveAll .el-tree {
    border: 1px solid #ccc;
    height: 180px;
    overflow-x: hidden;
  }

  .orgManager .label_table .moveAll .el-tree span {
    color: #333
  }

  .el-dropdown-menu__item .el-button {
    padding: 0;
    border: none
  }
</style>
